<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;

class Organization extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected static $unguarded = true;

    protected $table = 'organizations';

    /**
     * 根据ID获取数据
     *
     * @param $id
     * @param mixed $columns
     * @return array|Builder
     */
    public static function getDataByID($id, string $columns = ''){
        $data = self::query();
        if($columns){
            $data->find($id,$columns);
            return $data;
        }
        $val = $data->find($id);
        if (empty($val)) {
            return [];
        }
        $status_show =  getStatusValue($val['status']);

        //组织成员
        $membersList = OrganizationsMembers::getMembersList($id,true);
        if ($membersList['code'] != 200) {
            $members_total = 0;
        }else{
            $members_total = count($membersList['data']);
        }

        $coun = OrganizationsMembersExamine::query()->where(['organization_id'=>$val['id'],'status'=>1])->count();

        return [
            'id'=>$val['id'],
            'name'=>$val['name'],
            'status'=>$val['status'],
            'sort'=>$val['sort'],
            'first_letter'=>$val['first_letter'],
            'avatar'=>$val['avatar'],
            'create_user_id'=>$val['create_user_id'],
            'members_total'=>$members_total,
            'examine_num'=>$coun,
            'status_show'=>$status_show,
            'notice'=>empty($val['notice'])?'':$val['notice'],
            'crated_at'=>Carbon::parse($val['created_at'])->toDateTimeString(),
            'updated_at'=>Carbon::parse($val['updated_at'])->toDateTimeString(),
        ];
    }


    /**
     * @param $where
     * @param string $orderby
     * 根据条件获取列表
     */
    public static function  getDataList($where,$orderby='')
    {
        $data = self::query();

        if($where){
            $data->where($where);
        }
        if($orderby == 'sort'){
            $data->latest('sort');
        }
        if($orderby == 'all'){
            $data->oldest('id');
        }

        return $data->get();

        //Organization::query()->where($where)->oldest('sort')->get();
    }
}
